using System;
using System.Windows.Forms;
using WindowsLive.Writer.Api;
using System.Drawing;
using WIA;

namespace WebcamSnapshotPlugin
{
	[WriterPlugin( "DA1ACE5C-FF64-4e9e-A0E2-CC4B44308E2E", "WebcamSnapshot", 
		ImagePath = "Images.InsertSnapshot.png",
		PublisherUrl = "http://thopark.spaces.live.com",
        HasEditableOptions = true,
		Description = "Embed Webcam Snapshots in your blog posts.")]

	[InsertableContentSource( "Webcam Snapshot" )]
	public class SmartWebcamSnapshotPlugin : SmartContentSource
	{
		private WebcamSnapshotSettings _defaultSettings;
        private string SnapshotFile;
        System.Drawing.Image SnapshotImage;
        public SmartWebcamSnapshotPlugin()
		{
		}

        public override ResizeCapabilities ResizeCapabilities
        {
            get
            {
                return ResizeCapabilities.Resizable;
            }
        }

        public override void OnResizeStart(ISmartContent content, ResizeOptions options)
        {
            options.ResizeableElementId = "WebcamSnapshot";
            base.OnResizeStart(content, options);
        }

        public override void OnResizeComplete(ISmartContent content, System.Drawing.Size newSize)
        {
            string Filename = content.Files.Filenames[0];
            System.Drawing.Image ResizeImage = Image.FromStream(content.Files.Open(Filename,false));
            
            content.Files.AddImage(Filename, ResizeBitmap(ResizeImage, newSize.Width, newSize.Height), System.Drawing.Imaging.ImageFormat.Jpeg);
            base.OnResizeComplete(content, newSize);
        }

        public System.Drawing.Image ResizeBitmap(System.Drawing.Image OriginalImage, int width, int height)
        {
            Bitmap result = new Bitmap(width, height);

            using (Graphics g = Graphics.FromImage(result))
            using (SolidBrush brush = new SolidBrush(Color.Red))
            {
                // Draw the originam image in a new size.
                g.DrawImage(OriginalImage, 0, 0, width, height);
            }

            return System.Drawing.Image.FromHbitmap(result.GetHbitmap());
        }


		public override void Initialize(WindowsLive.Writer.Api.IProperties pluginOptions)
		{
			base.Initialize(pluginOptions);

			_defaultSettings = new WebcamSnapshotSettings(pluginOptions) ;
		}

		public override SmartContentEditor CreateEditor(ISmartContentEditorSite contentEditorSite)
		{
			return new SmartWebcamSnapshotContentEditor(contentEditorSite, _defaultSettings) ;
		}

		public override DialogResult CreateContent(IWin32Window dialogOwner, ISmartContent newContent)
		{
			WebcamSnapshotSettings settings = new WebcamSnapshotSettings(newContent.Properties);
            using (WebcamSnapshotInsertForm insertForm = new WebcamSnapshotInsertForm())
			{
                insertForm.DeviceId = _defaultSettings.DeviceId;
				DialogResult result = insertForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    settings.DeviceId = insertForm.DeviceId;
                    SnapshotFile = insertForm.SnapshotFile;
                    settings.SnapshotFile = SnapshotFile;
                    SnapshotImage = insertForm.SnapshotImage;
                    newContent.Files.AddImage(SnapshotFile, SnapshotImage, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                return result;
			}
		}

        public override string GenerateEditorHtml(ISmartContent content, IPublishingContext publishingContext)
        {
            WebcamSnapshotSettings settings = new WebcamSnapshotSettings(content.Properties);
            string PathToImage = content.Files.GetUri(settings.SnapshotFile).ToString();
            return String.Format("<img id=\"WebcamSnapshot\" src=\"{0}\"/>", PathToImage);
        }

		public override string GeneratePublishHtml(ISmartContent content, IPublishingContext publishingContext )
		{
            WebcamSnapshotSettings settings = new WebcamSnapshotSettings(content.Properties);
            string PathToImage = content.Files.GetUri(settings.SnapshotFile).ToString();
            return String.Format("<img src=\"{0}\"/>", PathToImage);
		}

        public override void EditOptions ( IWin32Window dialogOwner )
        {
            DoConfig();
            //base.EditOptions ( dialogOwner );
        }

        /// <summary>
        /// Show Device-Selection Dialog and store selected Device
        /// </summary>
        private void DoConfig()
        {
            string DeviceId = string.Empty;
            try
            {
                CommonDialogClass class1 = new CommonDialogClass ();
                Device d = class1.ShowSelectDevice ( WiaDeviceType.VideoDeviceType, true, false );
                if (d != null)
                {
                    DeviceId = d.DeviceID;
                }
                _defaultSettings.DeviceId = DeviceId;
                
            }
            catch (Exception ex)
            {
                PluginDiagnostics.DisplayError ( "Webcam Snapshot Error", "Device selection failed: " + ex.Message );
            }
        }
	}
}